package com.leemon.mall.sys.aspect;


import cn.hutool.core.date.SystemClock;
import com.leemon.mall.common.util.Json;
import com.leemon.mall.security.util.SecurityUtils;
import com.leemon.mall.sys.model.SysLog;
import com.leemon.mall.sys.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author limenglong
 * @create 2019-09-06 14:20
 * @desc 统一日志处理切面
 **/
@Component
@Aspect
@Slf4j
public class SysLogAspect {

    @Autowired
    private SysLogService sysLogService;

    @Around("@annotation(sysLog)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint, com.leemon.mall.common.annotation.SysLog sysLog) throws Throwable {
        long startTime = SystemClock.now();
        //执行方法
        Object proceed = proceedingJoinPoint.proceed();
        long endTime = SystemClock.now();


        //日志实体类
        SysLog sysLogEntity = new SysLog();

        sysLogEntity.setTime(endTime - startTime);

        //用户名
        String username = SecurityUtils.getSysUser().getUsername();
        sysLogEntity.setUsername(username);

        //获取注解上的描述
        if (sysLog != null) {
            sysLogEntity.setOperation(sysLog.value());
        }

        //获取方法名
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        String methodName = proceedingJoinPoint.getSignature().getName();
        sysLogEntity.setMethod(className + "." + methodName + "()");                                                   

        //参数
        Object[] args = proceedingJoinPoint.getArgs();
        String params = Json.toJsonString(args);
        sysLogEntity.setParams(params);


        //TODO 获取真实IP
        sysLogEntity.setIp("");


        sysLogEntity.setCreateDate(LocalDateTime.now());

        return null;
    }

}
